package com.yloveg.base;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.apache.log4j.Logger;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class HandlerExceptionResolverImpl extends SimpleMappingExceptionResolver {
    private final static Logger logger = Logger.getLogger(HandlerExceptionResolverImpl.class);

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request,
        HttpServletResponse response, Object handler, Exception ex) {
        logger.error(ex.getMessage(), ex);

        String viewName = determineViewName(ex, request);

        if (viewName != null) {
            if ((request.getHeader("accept") != null) &&
                    (!((request.getHeader("accept").indexOf("application/json") > -1) ||
                    ((request.getHeader("X-Requested-With") != null) &&
                    (request.getHeader("X-Requested-With")
                                .indexOf("XMLHttpRequest") > -1))))) {
                Integer statusCode = determineStatusCode(request, viewName);

                if (statusCode != null) {
                    applyStatusCodeIfPossible(request, response, statusCode);
                }

                return (getModelAndView(viewName, ex, request));
            } else {
                PrintWriter writer = null;

                try {
                    response.setCharacterEncoding("utf-8");
                    response.setContentType("application/json;charset=utf-8");
                    writer = response.getWriter();

                    /*  */
                    ObjectMapper mapper = new ObjectMapper();

                    if (ex instanceof MyException) {
                        writer.write(mapper.writeValueAsString(
                                new Result("500", ex.getMessage())));
                    } else {
                        writer.write(mapper.writeValueAsString(
                                new Result("500", ex.getMessage())));
                    }

                    writer.flush();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                } finally {
                    writer.close();
                }

                return (null);
            }
        } else {
            return (null);
        }
    }
}
